import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { showToast, showLoadingToast, closeToast } from 'vant'
import router from '@/router'

class Request {
  private instance: AxiosInstance
  private loading: boolean

  constructor(config: AxiosRequestConfig) {
    // 直接使用环境变量中配置的 baseURL
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_APP_API_BASE_URL,
      timeout: 10000,
      ...config
    })
    this.loading = false

    this.instance.interceptors.request.use(
      (config) => {
        if (!this.loading) {
          showLoadingToast({
            message: '加载中...',
            forbidClick: true,
          })
          this.loading = true
        }
        
        // 添加token
        const token = localStorage.getItem('token')
        console.log(token,111);
        
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    this.instance.interceptors.response.use(
      (response) => {
        if (this.loading) {
          closeToast()
          this.loading = false
        }
        
        const res = response.data
        console.log('Raw response:', response) // 添加原始响应日志
        console.log('Response data:', res) // 添加响应数据日志
        
        // 如果响应直接包含 token，直接返回整个响应
        if (res.token) {
          return res
        }
        
        // 检查返回的数据结构
        if (res.code !== 200) {
          return Promise.reject(new Error(res.message || '请求失败'))
        }
        
        // 返回数据部分
        return res.data
      },
      (error) => {
        if (this.loading) {
          closeToast()
          this.loading = false
        }
        
        console.error('Response Error:', error.response || error) // 详细的错误日志
        
        // 处理 401 未授权的情况
        if (error.response?.status === 401) {
          localStorage.removeItem('token')
          showToast('登录已过期，请重新登录')
          
          // 获取当前路由路径，用于登录后重定向回来
          const currentPath = router.currentRoute.value.fullPath
          
          // 跳转到登录页面，并带上重定向参数
          router.push(`/auth/login?redirect=${encodeURIComponent(currentPath)}`)
          
          return Promise.reject(error)
        }
        
        // 优先使用服务端返回的错误信息
        const message = error.response?.data?.message || error.message || '请求失败'
        showToast(message)
        return Promise.reject(new Error(message))
      }
    )
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config)
  }

  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config)
  }

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.post(url, data, config)
  }

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.put(url, data, config)
  }

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config)
  }
}

// 导出实例，不需要再传入 baseURL
export default new Request({})
